﻿using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using CalcSharp.Core;

namespace plug_stringutils
{
    public sealed class StrUtils
    {
        private StrUtils() { }
        private static byte[] string2bytes(string s)
        {
            List<byte> strdata = new List<byte>();
            int up, down;
            for (int i = 0; i < s.Length; i++)
            {
                up = s[i] & 0xF0;
                down = s[i] & 0x0F;
                strdata.Add((byte)(up >> 4));
                strdata.Add((byte)(down));
            }
            return strdata.ToArray();
        }

        public static string Str_app(string[] pars)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in pars) sb.Append(s);
            return sb.ToString();
        }

        public static double Str_cmp(string s1, string s2)
        {
            if (s1.ToUpper() == s2.ToUpper()) return 1;
            else return 0;
        }
        public static double Str_ccmp(string s1, string s2)
        {
            if (s1 == s2) return 1;
            else return 0;
        }
        public static double Str_occ(string s, string sub)
        {
            string[] arr = MiscCoreFuncts.split(s, sub.Length);
            double cnt = 0;
            foreach (string ss in arr)
            {
                if (ss == sub) cnt++;
            }
            return cnt;
        }
        public static string Str_regex(string s, string regex, string repl)
        {
            return Regex.Replace(s, regex, repl);
        }
        public static string Str_chr(string s, int pos)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(s[pos]);
            return sb.ToString();
        }
        public static string Str_substr(string s, int st, int l)
        {
            return s.Substring(st, l);
        }
        public static double Str_hash(string s)
        {
            return s.GetHashCode();
        }

        public static string Str_MD5(string s)
        {
            StringBuilder sb = new StringBuilder();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(string2bytes(s));
            foreach (byte hex in hash) sb.Append((hex.ToString("x2")));
            return sb.ToString();
        }

        public static string Str_SHA1(string s)
        {
            StringBuilder sb = new StringBuilder();
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(string2bytes(s));
            foreach (byte hex in hash) sb.Append((hex.ToString("x2")));
            return sb.ToString();
        }
    }
}
